package com.zae.session;

import com.zae.pojo.Configuration;
import com.zae.pojo.MapperStatement;

import java.lang.reflect.*;
import java.util.List;
import java.util.Map;

public class DefaultSqlSession implements SqlSession {
    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration){
        this.configuration = configuration;
    }


    public <E> List<E> findAll(String statementId, Object... params) throws Exception{
        Map<String, MapperStatement> statementMap = configuration.getMapperStatementMap();
        MapperStatement mapperStatement = statementMap.get(statementId);
        Executor executor = new SimpleExecutor();
        List<Object> execute = executor.execute(configuration,mapperStatement,params);
        return (List<E>) execute;
    }

    public <T> T findOne(String statement, Object... params) throws Exception{
        List<Object> objectList = findAll(statement, params);
        if(objectList.size() == 1){
            return (T) objectList.get(0);
        }else{
            throw new RuntimeException("返回参数不唯一或者为空");
        }
    }

    public <T> T getMapper(Class<?> aclass) {
        Object object = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{aclass}, new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //获取执行方法名
                String methodName = method.getName();
                //获取全限类名
                String className = method.getDeclaringClass().getName();
                //statementId
                String statementId = className+"."+methodName;
                //参数泛型化
                Type type = method.getGenericReturnType();
                if(type instanceof ParameterizedType){
                    //存在泛型，则调用findAll
                    List<Object> all = findAll(statementId, args);
                    return all;
                }
                return findOne(statementId,args);
            }
        });

        return (T) object;
    }
}
